package cn.ydxiaoshuai.tools.base;

import cn.ydxiaoshuai.tools.util.oConvertUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 小帅丶
 * @className ApiController
 * @Description 基础Controller
 * @Date 2020/5/14-14:42
 **/
@Slf4j
public class ApiRestController {
    /**这些对象何以直接被子类使用*/
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    /**
     * 基础请求头对象
     **/
    protected static final HttpHeaders httpHeaders = new HttpHeaders();

    static {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    /**
     * 错误信息
     **/
    protected String errorMsg = "";
    /**
     * 开始时间
     **/
    protected long startTime = 0;
    /**
     * 响应的内容
     **/
    protected String beanStr = "";
    /**
     * 耗时
     **/
    protected String timeConsuming = "";
    /**
     * 客户端
     **/
    protected String userAgent;
    /**
     * 用户ID
     **/
    protected String userId;
    /**
     * IP
     **/
    protected String ip;
    /**
     * 请求参数
     **/
    protected String param;
    /**
     * 请求URI
     **/
    protected String requestURI;
    /**
     * 请求API版本
     **/
    protected String version;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        //客户端
        String userAgent = request.getHeader("User-Agent");
        this.userAgent = userAgent;
        //用户ID
        String userId = ServletRequestUtils.getStringParameter(request, "userId","");
        this.userId = userId;
        //IP
        String ip = oConvertUtils.getIpAddrByRequest(request);
        this.ip = ip;
        //请求URI
        this.requestURI = request.getRequestURI();
        //接口版本(方便是否进行内容安全检查)
        String version = ServletRequestUtils.getStringParameter(request, "version","1");
        this.version = version;

    }
}
